package cn.cdiothree.converter;

import cn.cdiothree.DTO.OrderDTO;
import cn.cdiothree.dataobject.OrderItem;
import cn.cdiothree.enums.ResultEnum;
import cn.cdiothree.exception.SellException;
import cn.cdiothree.form.OrderForm;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
@Slf4j
/**
 * 将orderForm上面的信息传入到OrderDTO中
 */
public class OrderForm2OrderDTOConverter {
    public static OrderDTO convert(OrderForm orderForm){
        Gson gson=new Gson();
        OrderDTO orderDTO=new OrderDTO();

        orderDTO.setBuyerName(orderForm.getName());
        orderDTO.setBuyerPhone(orderForm.getPhone());
        orderDTO.setBuyerAddress(orderForm.getAddress());
        orderDTO.setUserId(orderForm.getUserId());

        List<OrderItem> orderItemList=new ArrayList<>();
        try {
        orderItemList=gson.fromJson(orderForm.getItems(),
                new TypeToken<List<OrderItem>>(){
                }.getType());
        }catch (Exception e){
            log.error("【对象转换】错误，string={}",orderForm.getItems());
            throw new SellException(ResultEnum.PARAM_ERROR);
        }
        orderDTO.setOrderItemList(orderItemList);

        return orderDTO;
        }
}
